/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.lczyfy.idcp.modules.sys.vueweb;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lczyfy.idcp.common.config.Global;
import com.lczyfy.idcp.common.persistence.Page;
import com.lczyfy.idcp.common.utils.ResponseCode;
import com.lczyfy.idcp.common.utils.ServerResponse;
import com.lczyfy.idcp.common.utils.StringUtils;
import com.lczyfy.idcp.common.web.BaseController;
import com.lczyfy.idcp.modules.sys.entity.Office;
import com.lczyfy.idcp.modules.sys.entity.Role;
import com.lczyfy.idcp.modules.sys.entity.User;
import com.lczyfy.idcp.modules.sys.service.OfficeService;
import com.lczyfy.idcp.modules.sys.service.SystemService;
import com.lczyfy.idcp.modules.sys.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 用户Controller
 * @author ThinkGem
 * @version 2013-8-29
 */
@Api(value = "user")
@RestController
@RequestMapping(value = "${apiPath}/sys/user")
public class UserVueController extends BaseController {
	@Autowired
	private SystemService systemService;
	@Autowired
	private OfficeService officeService;
	@ApiOperation(value = "查询用户管理",notes = "")
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "search",method = RequestMethod.POST) //查询用户
	public ServerResponse<User> search(@RequestBody User user, int pageNo, int pageSize) {
		Page<User> page =  systemService.findVue(new Page<User>(pageNo,pageSize),user);
		return new ServerResponse(ResponseCode.SUCCESS.getCode(), page);
	}
	@ApiOperation(value = "获取常量",notes = "")
	@RequestMapping(value = "const",method = RequestMethod.GET) //查询用户
	public ServerResponse<String> type() {
		List<String> typeList =  new LinkedList<String>();
		typeList.add(Global.getConfig("productName"));
		typeList.add(Global.getConfig("copyrightYear"));
		typeList.add(Global.getConfig("version"));
		return new ServerResponse<String>(typeList);
	}
	@ApiOperation(value = "退出登录",notes = "")
	@RequestMapping(value = "logout",method = RequestMethod.GET) //查询用户
	public ServerResponse<String> logout() {
		UserUtils.getSubject().logout();
		return ServerResponse.createBySuccessMessage("退出成功");
	}
	@ApiOperation(value = "添加用户",notes = "添加用户")
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "save",method = RequestMethod.POST) //添加用户
	public ServerResponse<String> create(@RequestBody User user) {
		if(StringUtils.isBlank(user.getPassword())&& StringUtils.isNotBlank(user.getId())){
			User findByuser = systemService.getUser(user.getId());
			user.setPassword(findByuser.getPassword());
		}
		if (user.getCompanyId()==null || user.getCompanyId().equals("")){
			user.setCompany(UserUtils.getUser().getCompany());
		}else{
			user.setCompany(officeService.get(user.getCompanyId()));
		}
		if (user.getOfficeId()==null || user.getOfficeId().equals("")){
			user.setOffice(UserUtils.getUser().getOffice());
		}else {
			user.setOffice(officeService.get(user.getOfficeId()));
		}
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
		}
		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
			ServerResponse.createBySuccessMessage( "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<String> roleIdList = user.getRoleIdList();
		for (Role r : systemService.findAllRole()){
			if (roleIdList.contains(r.getId())){
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
			UserUtils.clearCache();
			//UserUtils.getCacheMap().clear();
		}
		systemService.saveUser(user);
		return ServerResponse.createBySuccessMessage("保存用户成功");
	}
	@ApiOperation(value = "删除用户",notes = "删除用户")
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "delete",method = RequestMethod.DELETE) //删除用户列表
	public ServerResponse<String> delete(@RequestBody User user) {
		if(Global.isDemoMode()){
			return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
		}
		if (UserUtils.getUser().getId().equals(user.getId())){
			return ServerResponse.createByErrorMessage("删除用户失败, 不允许删除当前用户");
		}else if (User.isAdmin(user.getId())) {
			return ServerResponse.createByErrorMessage("删除用户失败, 不允许删除超级管理员用户");
		}else {
			systemService.deleteUser(user);
			return ServerResponse.deleteBySuccessMessage("删除用户成功");
		}

	}
	@ApiOperation(value = "通过用户id详情",notes = "获取详情")
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "findById/{id}",method = RequestMethod.GET) //菜单列表
	public ServerResponse<User> findById(@PathVariable String id) {
		User findByuser = systemService.getUser(id);
		findByuser.setCompanyName(findByuser.getCompany().getName());
		findByuser.setCompanyId(findByuser.getCompany().getId());
		findByuser.setOfficeId(findByuser.getOffice().getId());
		findByuser.setOfficeName(findByuser.getOffice().getName());;
		return  new ServerResponse(ResponseCode.SUCCESS.getCode(),findByuser) ;
	}
	@ApiOperation(value = "获取当前用户信息",notes = "获取当前登录用户信息")
	@RequiresPermissions("user")
	@RequestMapping(value = "infoData",method = RequestMethod.GET)
	public User infoData() {
		return UserUtils.getUser();
	}
//	@ApiOperation(value = "查询用户级联",notes = "")
//	@RequiresPermissions("sys:user:view")
//	@RequestMapping(value = "treeData/{officeId}",method = RequestMethod.GET)
//	public ServerResponse<User> treeData(@PathVariable  String officeId) {
//		List<User> list = systemService.findUserByOfficeId(officeId);
//		return  new ServerResponse(ResponseCode.SUCCESS.getCode(),list);
//	}
	@ApiOperation(value = "修改用户密码",notes = "修改密码")
	@RequiresPermissions("user")
	@RequestMapping(value = "modifyPwd",method = RequestMethod.PUT)
	public ServerResponse<String> modifyPwd(@RequestBody String oldPassword, String newPassword) {
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)){
			if(Global.isDemoMode()){
				return ServerResponse.createByErrorMessage("演示模式，不允许操作！");
			}
			if (SystemService.validatePassword(oldPassword, user.getPassword())){
				systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
				return ServerResponse.createBySuccessMessage("修改密码成功");
			}else{
				return ServerResponse.createByErrorMessage("修改密码失败，旧密码错误");
			}
		}
		return ServerResponse.createByErrorMessage("修改密码失败，系统错误");
	}
	@ApiOperation(value = "登录名是否有效",notes = "登录名是否有效")
	@ResponseBody
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "checkLoginName",method = RequestMethod.GET)
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName !=null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "treeData", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户组织机构树形图")
    public ServerResponse<List<Map<String, Object>>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type,
                                                              @RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Office> list = officeService.findList(isAll);
        for (int i=0; i<list.size(); i++){
            Office e = list.get(i);
            if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
                    && (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
                    && (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
                    && Global.YES.equals(e.getUseable())){
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("userIds",systemService.findUserByOfficeId(e.getId()));
                map.put("pId", e.getParentId());
                map.put("pIds", e.getParentIds());
                map.put("name", e.getName());
                if (type != null && "3".equals(type)){
                    map.put("isParent", true);
                }
                mapList.add(map);
            }
        }
        return new ServerResponse(ResponseCode.SUCCESS.getCode(), mapList);
    }
}
